package com.tg.app.activity.device.add;
import android.annotation.SuppressLint;
import android.content.Context;
import android.content.Intent;
import android.net.wifi.WifiInfo;
import android.net.wifi.WifiManager;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.text.TextUtils;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageButton;
import android.widget.TextView;
import androidx.annotation.NonNull;
import com.alibaba.fastjson.JSON;
import com.tange.base.toolkit.WifiAp;
import com.appbase.custom.constant.CommonConstants;
import com.demo.view.PopupWindowHelper;
import com.tange.module.camera.hub.CameraHub;
import com.tange.module.core.wifi.scan.ApScanConfiguration;
import com.tange.module.core.wifi.scan.WiFiScanManager;
import com.tg.app.R;
import com.base.BaseFragment;
import com.tg.appcommon.android.TGLog;
import com.tg.data.bean.DeviceItem;
import com.tg.data.bean.DeviceItem_;
import com.tg.app.camera.AVIOCTRLDEFs;
import com.tg.app.camera.Camera;
import com.tg.app.camera.Cs2Camera;
import com.tg.data.media.OnICameraListener;
import com.tg.app.listener.OnAddDeviceListener;
import com.tg.app.util.LogUtils;
import com.tg.app.util.ObjectBoxUtil;
import com.tange.base.toolkit.AppUtil;
import com.tg.appcommon.android.CustomInputStream;
import com.tange.base.toolkit.NetworkUtil;
import com.tange.base.toolkit.PreferenceUtil;
import com.tg.appcommon.android.TGAlertDialog;

import com.tg.network.socket.TGUDPSocket;
import com.tg.network.socket.UDPWifiSocket;

import java.util.ArrayList;
import java.util.Objects;

public class ApSearchFragment extends BaseFragment implements OnICameraListener, View.OnClickListener {
    public static final String TAG = ApSearchFragment.class.getSimpleName();
    private static final int CONNECT_SUCCEED = 0x01;
    private static final int CONNECT_FAILED = 0x02;
    private static final int CONNECT_SEARCH_WIFI_SUCCEED = 0x03;
    private static final int SEARCH = 0x04;
    private Camera camera;
    boolean isFirst = true;//第一次进入此界面不让其搜索设备
    private final ArrayList<String> wifiList = new ArrayList<>();
    private String ssid;
    private TGUDPSocket udpSocket;
    private PopupWindowHelper mPopupWindowHelper;
    private OnAddDeviceListener listener;
    private String p2pId = Camera.CS2_P2pID;
    @SuppressLint("HandlerLeak")
    private final Handler handler = new Handler() {
        @SuppressLint("DefaultLocale")
        @Override
        public void handleMessage(Message msg) {
            switch (msg.what) {
                case CONNECT_SUCCEED:
                    handler.removeMessages(CONNECT_FAILED);
                    if (CameraHub.getInstance().isEnableLocalApConnect()) {
                        addLocalDevice();
                        hideLoading();
                        if (listener != null) {
                            listener.onSetDeviceName(camera.deviceId, camera.uid, 0, "",1);
                        }
                    } else {
                        //连接成功搜索Wifi
                        getWifiList();
                    }
                    break;
                case CONNECT_FAILED:
                    hideLoading();
                    if (listener!=null){
                        listener.onSearchFailed();
                    }
                    showTipsPop();
                    LogUtils.uploadLogN("ApSearch",String.format("用户ID：%d，进行一次有线搜索，未搜索到设备", PreferenceUtil.getInt(getContext(), CommonConstants.PRE_USER_ID)));

                    break;
                case CONNECT_SEARCH_WIFI_SUCCEED:
                    hideLoading();
                    if (wifiList.size() > 0) {
                        if (listener != null) {
                            camera.unregisterICameraListener(ApSearchFragment.this);
                            Bundle args = new Bundle();
                            args.putStringArrayList(LanSearchFragment.EXT_LAN_SEARCH_RESULT, wifiList);
                            listener.onSearchDevice(args);
                        }
                    }
                    break;
                case SEARCH:
                    if (udpSocket != null) {
                        udpSocket.stopUDPSocket();
                    }
                    getWifiListFormCS2();
                    break;

            }
        }
    };





    public void setListener(OnAddDeviceListener listener) {
        this.listener = listener;
    }

    public ApSearchFragment() {

    }


    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        View view = inflater.inflate(R.layout.fragment_ap_search, container, false);
        view.findViewById(R.id.btn_ap_search_set_wifi).setOnClickListener(this);
        view.findViewById(R.id.how_to_connect_device).setOnClickListener(this);

        TextView tv = view.findViewById(R.id.connect_power);
        if (tv != null) {
            tv.setText(String.format(getString(R.string.open_device_wifi), ApScanConfiguration.INSTANCE.apNamePrefix()));
        }
        return view;
    }

    @Override
    public void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
    }

    @Override
    public void onResume() {
        super.onResume();
        /*
            尚云ap添加流程：
            设备打开Ap,app连接设备AP，直接使用固定的p2p_id去连接
         */
        if(isFirst) {
            isFirst = false;
        }else {
            if (listener!=null){
                listener.onSearchDeviceBegin();
            }
            getWIFIHz();
        }
    }

    private void getWIFIHz() {
        WifiManager manager = (WifiManager) requireContext().getApplicationContext().getSystemService(Context.WIFI_SERVICE);
        WifiInfo info = manager.getConnectionInfo();
        WifiAp wifiAp = NetworkUtil.getConnectWifiSSID(getContext());

        if (!TextUtils.isEmpty(wifiAp.ssid)&&wifiAp.ssid.startsWith(ApScanConfiguration.INSTANCE.apNamePrefix())){
            if (CameraHub.getInstance().isEnableLocalApConnect()){
                long count = Objects.requireNonNull(ObjectBoxUtil.getDeviceItem()).query().equal(DeviceItem_.uuid, wifiAp.ssid).build().count();
                if (count > 0) {
                    new TGAlertDialog(mActivity).builder().setTitle(R.string.ap_add_deivce_error).setMessage(R.string.ap_add_deivce_exist).setPositiveButton(R.string.confirm, new View.OnClickListener() {
                        @Override

                        public void onClick(View v) {
                          if (listener!=null){
                              listener.onSearchFailed();
                          }

                        }
                    }).show();
                    return;
                }
            }
            int frequency;
            if (android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.LOLLIPOP) {
                frequency = info.getFrequency();
                if (frequency > 2400 && frequency < 2500) {
                    ssid = wifiAp.ssid;
                    initSearch();
                } else {
                    if (listener!=null){
                        listener.onSearchFailed();
                    }
                }
            }

        }else {
            handler.sendEmptyMessage(CONNECT_FAILED);
        }
    }


    private void getWifiListFormCS2() {
        WiFiScanManager.scanner().setCameraUseWifiData(mActivity);
        camera = new Cs2Camera(ssid, p2pId, Camera.P2p_Name, Camera.P2p_PWD);
        camera.registerICameraListener(this);
        camera.enableLanSearch();
        handler.sendEmptyMessageDelayed(CONNECT_FAILED, 60000);//1分钟检测是否成功
        camera.connect();
    }

    private void getWifiList() {
        if (camera != null) {
            camera.sendIOCtrl(AVIOCTRLDEFs.IOTYPE_USER_IPCAM_LISTWIFIAP_REQ, new byte[4]);
        }
    }
    /* 本地直连相关 start**/

    /**
     * 添加新的直连设备
     */
    private void addLocalDevice() {
        int num = PreferenceUtil.getInt(mActivity, CommonConstants.PRE_DEVICE_LOCAL_NUM, 0) + 1;
        DeviceItem deviceItem = new DeviceItem();
        deviceItem.name = getString(R.string.camera) + num;
        deviceItem.p2p_id = p2pId;
        deviceItem.uuid = camera.uid;
        deviceItem.password = Camera.P2p_PWD;
        deviceItem.device_type = "wifi";
        Objects.requireNonNull(ObjectBoxUtil.getDeviceItem()).put(deviceItem);
    }

    /**
     * 本地直连相关 end
     **/


    private void showTipsPop() {
        if (mPopupWindowHelper != null && mPopupWindowHelper.isShowing()){
            return;
        }
        if (AppUtil.isActivityFinishingOrDestroyed(getActivity())){
            return;
        }
        mPopupWindowHelper = new PopupWindowHelper() {
            @Override
            protected void initView(@NonNull View view) {
                TextView tips = view.findViewById(R.id.tv_ap_tips_setup_two_content);
                String tipsText = String.format(getResources().getString(R.string.ap_tips_setup_two_description), ApScanConfiguration.INSTANCE.apNamePrefix());
                tips.setText(tipsText);
            }

            @Override
            protected void setTouchable() {
                mPopupWindowHelper.setTouchableImpl(true, false, false);
            }

            @SuppressLint("ClickableViewAccessibility")
            @Override
            protected void setPopupWindowListener(@NonNull View view) {
                ImageButton close_btn = view.findViewById(R.id.add_close);
                close_btn.setOnClickListener(v -> mPopupWindowHelper.dismissPopupWindow());
                mPopupWindowHelper.getPopupWindow().setTouchInterceptor((v, event) -> {
                    return false;
                    // 这里如果返回true的话，touch事件将被拦截
                    // 拦截后 PopupWindow的onTouchEvent不被调用，这样点击外部区域无法dismiss
                });
                mPopupWindowHelper.setOnDismissListener(() -> mPopupWindowHelper.setOldAttributes(getActivity()));
            }
        };

        mPopupWindowHelper.showPopupWindow(getActivity(), R.layout.ap_add_tip_pop, getView(), Gravity.CENTER);
    }

    @Override
    public void receiveUpdateConnectStates(int state) {
        if (state == Camera.CONNECTION_STATE_CONNECTED) {
            handler.sendEmptyMessage(CONNECT_SUCCEED);
        }
    }

    @Override
    public void onStop() {
        super.onStop();
        if (camera != null) {
            camera.unregisterICameraListener(this);
        }
        handler.removeCallbacksAndMessages(null);
    }

    @Override
    public void receiveIOCtrlData(int type, byte[] data) {
        if (camera != null) {
            if (type == AVIOCTRLDEFs.IOTYPE_USER_IPCAM_LISTWIFIAP_RESP) {
                {
                    wifiList.clear();
                    CustomInputStream.InputStream stream = new CustomInputStream.InputStream(data);
                    int num = stream.getInt();
                    num = Integer.reverseBytes(num);
                    if (num > 0) {
                        for (int i = 0; i < num; i++) {
                            WifiAp wifiAp  = new WifiAp();
                            wifiAp.ssid = stream.getString(32);
                            wifiAp.mode = stream.getByte();
                            wifiAp.enctype = stream.getByte();
                            wifiAp.signal = stream.getByte();
                            wifiAp.status = stream.getByte();
                            if (!TextUtils.isEmpty(wifiAp.ssid)) {
                                wifiList.add(JSON.toJSONString(wifiAp));
                            }
                        }
                        handler.sendEmptyMessage(CONNECT_SEARCH_WIFI_SUCCEED);
                    }
                }
            }
        }

    }

    private void initSearch() {
        udpSocket = new UDPWifiSocket(getActivity());
        udpSocket.setClientPort(TGUDPSocket.AP_CLIENT_PORT);
        udpSocket.setOnReceiveUDPSocketLister(device -> {
            p2pId = device.p2pid;
            TGLog.i(TAG, "OnReceiveUDPSocketLister = " + JSON.toJSONString(device));
            udpSocket.stopUDPSocket();
            handler.removeMessages(SEARCH);
            getWifiListFormCS2();
        });
        search();
    }
    private void search() {
        showLoading();
        udpSocket.startUDPSocket();
        udpSocket.startSearchDevice();
        //搜索3秒
        handler.sendEmptyMessageDelayed(SEARCH, 1000 * 2);
    }

    @Override
    public void onClick(View view) {
        int id = view.getId();
        if (id == R.id.how_to_connect_device) {
            showTipsPop();
        } else if (id == R.id.btn_ap_search_set_wifi) {
            Intent intent = new Intent();
            intent.setAction("android.net.wifi.PICK_WIFI_NETWORK");
            startActivity(intent);
        }
    }

}
